package kim.sesame.util.excel;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.util.Set;

/**
 * 设置指定列为文本格式的写处理器
 */
@Data
@AllArgsConstructor
public class TextFormatSheetWriteHandler implements SheetWriteHandler {

    /**
     * 需要设置为文本格式的列索引集合
     */
    private final Set<Integer> textFormatColumnIndexes;

    @Override
    public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        // 无需实现
    }

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        Sheet sheet = writeSheetHolder.getSheet();
        Workbook workbook = writeWorkbookHolder.getWorkbook();

        // 创建文本格式的样式
        CellStyle textStyle = workbook.createCellStyle();
        DataFormat dataFormat = workbook.createDataFormat();
        textStyle.setDataFormat(dataFormat.getFormat("@")); // "@" 表示文本格式

        // 为指定列设置文本格式
        for (Integer columnIndex : textFormatColumnIndexes) {
            // 设置列的默认样式为文本格式
            sheet.setDefaultColumnStyle(columnIndex, textStyle);
        }
    }
}